package itbour.onetouchshow.fragment.challengezone;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.just.agentwebX5.AgentWebX5;
import com.just.agentwebX5.ChromeClientCallbackManager;
import com.lsjr.net.RequestParams;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.Unbinder;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_3.MainActivityV3;
import itbour.onetouchshow.activity.web.CommWebJsContrl;
import itbour.onetouchshow.base.mvp.MVPBaseFragment;
import itbour.onetouchshow.bean.JcmSetNavButtonBean;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.EncryptUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.video.StatusBarUtils;
import itbour.onetouchshow.view.NavigationBarView;

/**
 * Created by guoh on 2018/6/12.
 * 功能描述：挑战专区
 * 需要的参数：
 */
public class ChallengeAreaFragment extends MVPBaseFragment {

    protected AgentWebX5 mAgentWeb;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.navi)
    NavigationBarView navi;
    @BindView(R.id.v_status_bar)
    View vStatusBar;
    Unbinder unbinder;

    //页面是否第一次创建
    private boolean isFirstCreate = true;

    private Handler uiHandler;

    private JcmSetNavButtonBean jcmSetNavButtonBean;
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            navi.setTitleText(view.getTitle());
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            L_.e("暂无网络 onReceivedError");
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            L_.e("暂无网络 onReceivedHttpError");
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            L_.e("暂无网络 onReceivedSslError");
        }


    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.i("Info", "progress:" + newProgress);
        }


    };
    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (!title.contains("网页无法")) {
                navi.setTitleText(title);
            }

        }
    };

    public void setJcmSetNavButtonBean(JcmSetNavButtonBean jcmSetNavButtonBean) {
        this.jcmSetNavButtonBean = jcmSetNavButtonBean;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fr_challenge_are;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
    }

    private void initStatusBar() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vStatusBar.getLayoutParams();
        params.height = StatusBarUtils.getStatusBarHeight(getActivity());
        vStatusBar.setLayoutParams(params);
        vStatusBar.setBackgroundColor(getResources().getColor(R.color.app_status_bar_color));
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        initStatusBar();
        uiHandler = new Handler();
        navi.setBackgroundColor(getResources().getColor(R.color.app_status_bar_color));
        navi.setTitleTextColor(getResources().getColor(R.color.white));
        navi.getLeftimageView().setVisibility(View.GONE);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        RequestParams requestParams = null;
        requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.CHALLENGE_AREA);
        String url = EncryptUtils.getPrintHtmlUrl(requestParams);
        initAgentWeb(url);
        CommWebJsContrl commWebJsContrl = new CommWebJsContrl((MainActivityV3) getActivity(), this);
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AppConst.CONTRL, commWebJsContrl);
        exuJsPageStatueMethod(1, getStateType());
    }

    private void setLeftBackImage() {
        if (getWebView().canGoBack()) {
            navi.getLeftimageView().setImageResource(R.mipmap.return_icon);
        } else {
            navi.getLeftimageView().setImageResource(R.mipmap.cancle_icon);
        }
    }

    protected AgentWebX5.CommonAgentBuilder getWebBuilder() {
        long p = System.currentTimeMillis();
        return AgentWebX5.with(getActivity())
                //new LinearLayout.LayoutParams(-1, -1)
                .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1))
                //.useDefaultIndicator()
                //.defaultProgressBarColor()
                // .setIndicatorColor(UIUtils.getColor(R.color.apptheme))
                .closeProgressBar()
                .setReceivedTitleCallback(mCallback).
                        setWebChromeClient(mWebChromeClient).
                        setWebViewClient(mWebViewClient).
                        setSecutityType(AgentWebX5.SecurityType.strict);
    }

    public WebView getWebView() {
        WebView mWebView = null;
        if (mAgentWeb != null) {
            mWebView = mAgentWeb.getWebCreator().get();
        }
        return mWebView;

    }

    public void initAgentWeb(String url) {
        mAgentWeb = getWebBuilder().createAgentWeb().ready().go(url);
        getWebView().setBackgroundColor(UIUtils.getColor(android.R.color.transparent));
        getWebView().setBackgroundResource(R.color.apptheme_bg);
        if (App.testWhendebug()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // getWebView().setWebContentsDebuggingEnabled(true);
            }
        }
        //设置 缓存模式
        getWebView().getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        getWebView().getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        getWebView().getSettings().setDatabaseEnabled(true);
        // getWebView().getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        // getWebView().getSettings().setDomStorageEnabled(true);

        WebSettings webSetting = getWebView().getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(getActivity().getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(getActivity().getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(getActivity().getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        CookieSyncManager.createInstance(getActivity());
        CookieSyncManager.getInstance().sync();

    }

    public void showRightTitle(int show, String title) {
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(title)) {
                    navi.getRightTextView().setVisibility(View.GONE);
                    return;
                }
                navi.setRightText(title).setVisibility(show == 0 ? View.VISIBLE : View.GONE);
                navi.getRightTextView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (jcmSetNavButtonBean != null) {
                            String success = jcmSetNavButtonBean.getSuccess();
                            if (!TextUtils.isEmpty(success)) {
                                String call = "javascript:" + success + "()";
                                getWebView().loadUrl(call);
                            }
                        }

                    }
                });


            }
        });
    }

    public void showRightImage(int show, int content) {
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                switch (content) {
                    //分享图标
                    case 1:
                        navi.getRightImageView().setImageResource(R.mipmap.icon_activity_share);
                        break;
                }
                navi.getRightImageView().setVisibility(show == 0 ? View.VISIBLE : View.GONE);
                navi.getRightImageView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (jcmSetNavButtonBean != null) {
                            String success = jcmSetNavButtonBean.getSuccess();
                            if (!TextUtils.isEmpty(success)) {
                                String call = "javascript:" + success + "()";
                                getWebView().loadUrl(call);
                            }
                        }

                    }
                });
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        exuJsPageStatueMethod(2, getStateType());
    }

    @Override
    public void onPause() {
        super.onPause();
        //pause后置为false
        isFirstCreate = false;
        exuJsPageStatueMethod(3, getStateType());
    }

    @Override
    public void onStop() {
        super.onStop();
        exuJsPageStatueMethod(4, getStateType());
    }


    @Override
    public void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        super.onDestroy();
        exuJsPageStatueMethod(-1, getStateType());
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    private int getStateType() {
        return isFirstCreate ? 1 : 0;
    }

    private void exuJsPageStatueMethod(int status, int stateType) {
        //"stateType":1  1.表示创建时，0表示从其它页面回来
        String js = "var event = new CustomEvent('pageStateEventCallBack', {detail:{mobile_page_state_callBack:{state:" + status + ",stateType:" + stateType + "}}});document.dispatchEvent(event);";
        getWebView().evaluateJavascript(js, null);
    }

}
